<template>
  <div>
    <quill-editor
      v-model="remarkContent"
      class="editor"
      ref="myQuillEditor"
      :options="editorOption"
      @blur="onEditorBlur($event)"
      @focus="onEditorFocus($event)"
      @change="onEditorChange($event)"
    >
    </quill-editor>
    <div style="text-align:right;" v-if="showNumberTip">{{ tiLength }}/{{ maxLength }}</div>
    <span style="color:#f90" v-if="showParseTip">
      <Icon
        type="ios-information-circle-outline"
      />仅允许粘贴文本内容，粘贴内容中的图片、链接和样式将无效</span
    >
    <Upload
      ref="upload"
      style="display:inline-block"
      :show-upload-list="false"
      :on-success="handleSuccess"
      :on-exceeded-size="onExceededSizeImg"
      :on-format-error="handleFormatErrorImg"
      :format="['jpg', 'jpeg', 'png', 'gif']"
      multiple
      :action="uploadUrl"
    >
      <Button icon="ios-cloud-upload-outline" id="imgUploadBtn" v-show="false"></Button>
    </Upload>
    <Upload
      ref="fileUpload"
      style="display:inline-block"
      :show-upload-list="false"
      :on-success="handleFileSuccess"
      :on-exceeded-size="onExceededSizeFile"
      :on-format-error="handleFormatErrorFile"
      :format="['pdf']"
      multiple
      :action="fileUploadUrl"
    >
      <Button icon="ios-cloud-upload-outline" id="fileUploadBtn" v-show="false"></Button>
    </Upload>
  </div>
</template>

<script>
import { quillEditor } from 'vue-quill-editor'; // 调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
//引入Qill插件
import Quill from 'quill';
let Link = Quill.import('formats/link');
// 自定义a链接
class FileBlot extends Link {
  // 继承Link Blot
  static create(value) {
    let node = undefined;
    if (value && !value.href) {
      // 适应原本的Link Blot
      node = super.create(value);
    } else {
      // 自定义Link Blot
      node = super.create(value.href);
      node.innerText = value.innerText;
      node.href = value.href;
      node.id = value.id;
      node.setAttribute('title', '点击可下载:' + value.innerText);
      node.setAttribute('data-value', value.dataValue);
    }
    return node;
  }
}
FileBlot.blotName = 'link';
FileBlot.tagName = 'A';
//注册FileBlot
Quill.register(FileBlot);

const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
  [{ header: 1 }, { header: 2 }], // 1、2 级标题
  [{ script: 'sub' }, { script: 'super' }], // 上标/下标
  [{ indent: '-1' }, { indent: '+1' }], // 缩进
  [{ size: ['small', false, 'large', 'huge'] }], // 字体大小
  [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
  [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
  [{ align: [] }], // 对齐方式
  ['clean'], // 清除文本格式
  ['image'], // 链接、图片、视频
  ['file'] // 文件链接
];
export default {
  components: {
    quillEditor
  },
  props: {
    value: {
      type: String,
      default: ''
    },
    maxLength: {
      type: Number,
      default: 500
    },
    showNumberTip: {
      type: Boolean,
      default: true
    },
    showParseTip: {
      type: Boolean,
      default: true
    }
  },
  mounted() {
    this.remarkContent = this.value;
  },
  watch: {
    value(newValue) {
      this.remarkContent = newValue;
    }
  },
  data() {
    return {
      tiLength: 0,
      uploadUrl: '/api/minio/upload/permanent?visibility=company&type=images&bucket=images',
      fileUploadUrl: '/api/minio/upload/permanent?visibility=company&type=docs&bucket=docs',
      editorOption: {
        modules: {
          clipboard: {
            // 粘贴版，处理粘贴时候带图片
            matchers: [[Node.ELEMENT_NODE, this.handleCustomMatcher]]
          },
          toolbar: {
            container: toolbarOptions, //工具菜单栏配置
            handlers: {
              image: (value) => {
                if (value) {
                  document.querySelector('#imgUploadBtn').click();
                } else {
                  this.quill.format('image', false);
                }
              },
              file: (value) => {
                if (value) {
                  document.querySelector('#fileUploadBtn').click();
                }
              }
            }
          }
        },
        placeholder: '请输入内容' //提示
      },
      remarkContent: ''
    };
  },
  methods: {
    reset() {
      this.remarkContent = '';
      this.$emit('input', this.remarkContent);
    },
    // 格式验证失败时的回调函数
    handleFormatErrorFile() {
      this.$Message.warning('仅允许上传pdf格式文件');
    },
    // 上传文件，上传成功后将文件地址生成超链接插入富文本光标处
    handleFileSuccess(res) {
      if (res.code == 1) {
        // 获取光标所在位置
        let quill = this.$refs.myQuillEditor.quill;
        let length = quill.getSelection().index || 1;
        // 插入图片，res为服务器返回的图片链接地址
        let url = `${this.baseURL}/minio/download?path=${res.data}`; // `/Learn/${res.data}`
        quill.insertEmbed(length, 'text', '[');
        quill.insertEmbed(
          length + 1,
          'link',
          {
            href: url,
            innerText: res.info.originalName,
            id: res.info.id,
            dataValue: `/Learn/${res.data}`
          },
          'api'
        );
        quill.insertEmbed(length + res.info.originalName.length + 1, 'text', ']');
      } else {
        this.$Message.error(data.message);
      }
    },
    // 图片格式验证失败时的回调函数
    handleFormatErrorImg() {
      this.$Message.warning('仅允许上传jpg,jpeg,png,gif格式文件');
    },
    onExceededSizeImg(file, fileList) {
      if (file) {
        this.$Message.warning('图片大小不得超过2M');
      }
    },
    onExceededSizeFile(file, fileList) {
      if (file) {
        this.$Message.warning('文件大小不得超过20M');
      }
    },
    // 上传图片，上传成功后使用图片地址生成img元素插入富文本光标处
    handleSuccess(res) {
      if (res.code == 1) {
        // 获取光标所在位置
        let quill = this.$refs.myQuillEditor.quill;
        let length = quill.getSelection().index;
        // 插入图片，res为服务器返回的图片链接地址
        let url = `/Learn/${res.data}`;
        quill.insertEmbed(length, 'image', url);
      } else {
        this.$Message.error(data.message);
      }
    },
    // 以下三个为富文本的相关事件回掉函数，用于后续扩展，暂时保留
    onEditorBlur() {}, // 失去焦点事件
    onEditorFocus() {}, // 获得焦点事件
    onEditorChange(event) {
      // 内容改变事件
      if (this.remarkContent === '') {
        this.tiLength = 0;
      } else {
        this.tiLength = event.quill.getLength() - 1;
      }
      if (this.tiLength > this.maxLength) {
        event.quill.deleteText(this.maxLength, this.tiLength - this.maxLength);
      }
      this.$emit('input', this.remarkContent);
    },
    // 粘贴时候，除纯文本外的内容全部忽略
    handleCustomMatcher(node, Delta) {
      let ops = [];
      Delta.ops.forEach((op) => {
        if (op.insert && typeof op.insert === 'string') {
          // 只有纯文本是字符串类型，其他包括图片、文件等，均忽略掉
          ops.push({
            // 只保留粘贴内容，格式全部舍弃
            insert: op.insert
          });
        }
        if (op.insert && op.insert.image && op.insert.image.indexOf('/Learn') !== -1) {
          ops.push({
            // 保留本系统包含的图片
            insert: op.insert
          });
        }
      });
      Delta.ops = ops;
      return Delta;
    }
  }
};
</script>
<style scoped>
/deep/ .ivu-modal-body .editor .ql-editor {
  min-height: 100px;
  max-height: 200px;
}
</style>
<style>
/* 文件上传图标样式 */
/* .editor .ql-formats .ql-file {
  background: url("../../assets/menu-icon/archive-icon-active.png");
  background-size: 16px 16px;
  background-position: center center;
  background-repeat: no-repeat;
  color: aquamarine;
} */
.ql-snow.ql-toolbar button.ql-file {
    font-size: 16px;
    display: inline-block;
    font-family: Ionicons;
    font-style: normal;
    font-weight: 400;
    font-variant: normal;
    text-transform: none;
    text-rendering: optimizeLegibility;
    line-height: 1;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    vertical-align: -0.125em;
    text-align: center;
    color: var(--default-color);
    /* color: #999; */
}
.ql-snow.ql-toolbar button.ql-file:before {
    content: '\F255';
    /*"PDF"*/
}
</style>
